package mv.releaser.view;

import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.AbstractList;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.swing.JComponent;
import javax.swing.JPanel;
import javax.swing.TransferHandler;

public class FileTransferHandler extends TransferHandler {

	private MainJPanel	parent;

	public FileTransferHandler(MainJPanel parent) {
		super();
		this.parent = parent;
	}

	@Override
	public boolean canImport(JComponent arg0, DataFlavor[] arg1) {
		System.out.println("dans canImport");
		for (DataFlavor data : arg1) {
			String mime = data.getHumanPresentableName();
			if (mime.equals("application/x-java-file-list")
					|| mime.equals("text/uri-list")) {
				return true;
			}
		}
		return false;
	}

	@Override
	public boolean importData(JComponent arg0, Transferable t) {

		for (DataFlavor data : t.getTransferDataFlavors()) {
			String mime = data.getHumanPresentableName();
			if (mime.equals("text/uri-list")
					|| mime.equals("application/x-java-file-list")) {
				AbstractList<File> files = getFileListString(t, data);
				if (files == null)
					return true;
				for (File f : files) {
					if (f.isFile())
						parent.openAviFile(f);
				}
				return true;
			}
		}
		return true;
	}

	private AbstractList<File> getFileListString(Transferable t,
			DataFlavor flavor) {
		try {
			Object data = t.getTransferData(flavor);
			if (data instanceof InputStreamReader) {
				AbstractList<File> files = new ArrayList<File>();
				BufferedReader in = new BufferedReader((InputStreamReader) t
						.getTransferData(flavor));
				String entry;
				while ((entry = in.readLine()) != null) {
					try {
						files.add(new File(new URI(entry)));
					} catch (IllegalArgumentException e) {
					} catch (URISyntaxException e) {
					}
				}
				return files;
			} else {
				return (AbstractList<File>) t.getTransferData(flavor);
			}
		} catch (UnsupportedFlavorException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

}
